package com.sdkj.fixed.asset.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 下载文件
 *
 * @author fengshuonan
 * @Date 2019/8/7 23:14
 */
public class FileDownload {

	/**
	 * @param response
	 * @param filePath		//文件完整路径(包括文件名和扩展名)
	 * @param fileName		//下载后看到的文件名
	 * @return  文件名
	 */
	public static void fileDownload(final HttpServletResponse response, HttpServletRequest request, String filePath, String fileName) throws Exception{
		String userAgent = request.getHeader("User-Agent");//获取浏览器名（IE/Chome/firefox）
		if (userAgent.contains("firefox")) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
		} else if (userAgent.contains("MSIE")) {
			fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
		}else if (userAgent.contains("CHROME")) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
		}
		//headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名
		byte[] data = FileUtil.toByteArray2(filePath);
	    fileName = URLEncoder.encode(fileName, "UTF-8");
	    response.reset();
	    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	    response.addHeader("Content-Length", "" + data.length);
	    response.setContentType("application/octet-stream;charset=UTF-8");
	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
	    outputStream.write(data);
	    outputStream.flush();
	    outputStream.close();
	    response.flushBuffer();
	}

	/**
	 * 下载图片
	 * @param picUrl
	 * @param savePath
	 * @param filename
	 * @throws IOException
	 */
	public static void DownloadPicture(String picUrl, String savePath, String filename) throws IOException {
		InputStream is = null;
		OutputStream os = null;
		try {
			URL url = new URL(picUrl);
			// 打开连接
			URLConnection con = url.openConnection();
			//设置请求的路径
			con.setConnectTimeout(10*1000);
			// 输入流
			is = con.getInputStream();

			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf=new File(savePath);
			if(!sf.exists()){
				sf.mkdirs();
			}
			os = new FileOutputStream(sf.getPath()+"/"+filename+".jpg");
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
		} finally {
			// 完毕，关闭所有链接
			if( null != os){
				os.close();
			}
			if( null != is ){
				is.close();
			}

		}


	}


}
